import { lazy } from "react"
import { Navigate, Outlet, RouteObject, RouterProvider, createBrowserRouter, redirect } from "react-router-dom"
import { Provider } from "react-redux"
import Left2Right from "@/Layout/Left2Right"
import Home from "@/pages/Home"
import Login from "@/pages/Login"
import ErrorPage from '@/pages/ErrorPage'
import Top2Bottom from "@/Layout/Top2Bottom"
import store from '@/store'

const About = lazy(() => import('@/pages/About'))
const CustomForm = lazy(() => import('@/pages/CustomForm'))
const CustomTable = lazy(() => import('@/pages/CustomTable'))
const ComplexTable = lazy(() => import('@/pages/ComplexTable'))

function loginLoader() {
  const token = localStorage.getItem('token')
  if (token) {
    return redirect('/')
  }
  return null
}

function authLoader() {
  const token = localStorage.getItem('token')
  if (token) {
    return null
  }

  return redirect('/login')
}

const routes: RouteObject[] = [
  { 
    path: 'login',
    loader: loginLoader,
	 	element: <Login />
  },

  {
    path: '/',
    element: <Left2Right />,
    // element: <Top2Bottom />,
    loader: authLoader,
    errorElement: <ErrorPage />,

    children: [
      { 
        index: true, 
        element: <Navigate to="home" replace />
      },

      {
        path: 'home',
        element: <Home />
      },

      {
        path: 'about',
        element: <About />
      },

      {
        path: 'components',
        element: <Outlet />,
        children: [
          {
            path: 'form',
            element: <CustomForm />
          },
          {
            path: 'table',
            element: <CustomTable />
          },
          {
            path: 'complex-table',
            element: <ComplexTable />
          }
        ]
      },
    ]
  }
]

const router = createBrowserRouter(routes)

const LayoutRouter = () => {
  return (
    <Provider store={store}>
      <RouterProvider router={router}/>
    </Provider>
  )
}

export default LayoutRouter